package com.codeduck.demo.simple;

import com.alibaba.fastjson.JSON;
import com.codeduck.constant.KafkaConst;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author: <a href="mailto:codeduck@163.com">codeduck</a>
 * @date: 2023/01/14
 */
@Service
@Slf4j
public class SimpleProducer {

    @Resource
    private KafkaTemplate<Object, Object> kafkaTemplate;
//    @Scheduled(cron = "0/1 * * * * ?")
    public void sendMessage() {
        String key = "dog";
        HashMap<String, String> value = new HashMap<>();
        int partition = new Random().nextInt(3);
        value.put("name", "旺财");
        value.put("skinColor", "black");
        value.put("time", LocalDateTime.now().toString());
        value.put("partition", partition +"");
        kafkaTemplate.send(KafkaConst.SIMPLE_TOPIC, partition, key, JSON.toJSONString(value));
        kafkaTemplate.flush();
        log.info("====================消息已发送 topic[{}], partition[{}]=====================", KafkaConst.SIMPLE_TOPIC, partition);
    }
}
